<template>
	<van-nav-bar title="收货地址" left-text="" left-arrow @click-left="goBack" />
	<!-- 确认订单 -->
	<van-address-list
		v-if="action"
		v-model="chosenAddressId"
		:list="list"
		default-tag-text="默认"
		@add="onAdd"
		@edit="onEdit"
		@select="Cahngeselected"
	/>
	<van-address-list
		v-else
		v-model="chosenAddressId"
		:list="list"
		default-tag-text="默认"
		@add="onAdd"
		@edit="onEdit"
		@select="chooseAddress"
	/>
</template>
<script setup>
	const router = useRouter();
	const route = useRoute();
	const action = ref(route.query.action ?? "");
	let { cookies } = useCookies();
	let LoginUser = reactive(cookies.get("LoginUser"));
	const goBack = () => {
		if (action.value != "") {
			history.back();
		}
		router.push("/business/index");
	};
	const chosenAddressId = ref("1");
	const list = reactive([]);
	onBeforeMount(() => {
		getAddress();
	});
	onMounted(() => {
		//监听页面卸载（关闭）或刷新
		window.addEventListener('beforeunload', () => unloadHandler())
	});
	// 关闭浏览器
	const unloadHandler=() => {
		cookies.remove("Address");
	}

	// 获取地址列表
	let getAddress = async () => {
		let result = await Api.business.getAddressList({ busid: LoginUser["id"] });
		if (result.code == 1) {
			result.data.forEach((item, index) => {
				let address = {
					id: item.id,
					name: item.consignee,
					tel: item.mobile,
					address: item.region_text + item.address,
					busid: item.busid,
				};
				if (item.status == 1) {
					address.isDefault = true;
					chosenAddressId.value = item.id;
				}
				list.push(address);
			});
		}
	};

	const onAdd = () => {
		router.push("/business/address/add");
	};
	const onEdit = (item, index) =>
		router.push("/business/address/edit?id=" + item.id);
	// 设置默认地址
	const chooseAddress = async (item, index) => {
		let data = {
			id: item.id,
			busid: item.busid,
		};
		let indexDefault = "";
		let idDefault = "";
		list.forEach((item, i) => {
			if ("isDefault" in item) {
				indexDefault = i;
				idDefault = item.id;
			}
		});
		let result = await Api.business.setDefault(data);
		if (result.code == 1) {
			if (indexDefault) {
				delete list[indexDefault].isDefault;
			}
			list[index].isDefault = true;
		} else {
			if (idDefault) {
				chosenAddressId.value = idDefault;
			}
			showSuccessToast(result.msg);
		}
	};
	const Cahngeselected = (item) => {
		// 存储用户选中的地址信息
		cookies.set("Address", {
			id: item.id,
			mobile: item.tel,
			consignee: item.name,
		});
		goBack();
	};

</script>